package com.example.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 使用HashOperations来简化Hash相关的操作
    private HashOperations<String, String, Object> hashOperations;

    @PostConstruct
    public void init() {
        // 初始化HashOperations
        hashOperations = redisTemplate.opsForHash();
    }

    public void saveToRedis(Map<String, Object> map, String key) {
        hashOperations.putAll(key, map);
    }

    /**
     * 获取Redis中指定key的整个Hash
     *
     * @param key Hash的key
     * @return 返回整个Hash的Map，如果key不存在则返回null
     */
    public Map<String, Object> getEntireHashFromRedis(String key) {
        return hashOperations.entries(key);
    }

    /**
     * 获取Redis中指定key的Hash中特定字段的值
     *
     * @param key   Hash的key
     * @param field Hash中的字段名
     * @return 返回字段对应的值，如果key或field不存在则返回null
     */
    public Object getFieldFromHash(String key, String field) {
        return hashOperations.get(key, field);
    }
}